package com.itheima.dubbo.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.model.enums.CommentType;
import com.itheima.model.mongo.Comment;
import com.itheima.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /*保存评论*/
    @Override
    public Integer save(Comment comment) {

        //将Movement中的评论/点赞/喜欢数+1
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));

        Update update = new Update();
        if(comment.getCommentType()== CommentType.LIKE.getType()){
            update.inc("likeCount",1);
        }else if (comment.getCommentType()== CommentType.COMMENT.getType()){
            update.inc("commentCount",1);
        }else {
            update.inc("loveCount",1);
        }
        FindAndModifyOptions op = new FindAndModifyOptions();
        op.returnNew(true);
        Movement resMovement = mongoTemplate.findAndModify(query, update, op, Movement.class);
        //保存评论
        if (resMovement!=null){
            comment.setPublishUserId(resMovement.getUserId());
        }
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);//保存评论数
        return resMovement.statisCount(comment.getCommentType());
    }
    //查看所有评论
    @Override
    public List<Comment> findComments(String movementId, CommentType comment, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType").is(comment.getType())).with(PageRequest.of(page-1, pagesize));
        return mongoTemplate.find(query,Comment.class);

    }
    //判断点赞/收藏/评论是否已经点过
    @Override
    public boolean hasComment(String movementId, Long userId, CommentType like) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("userId").is(userId).and("commentType").is(like.getType()));
        return mongoTemplate.exists(query,Comment.class);
    }
    //取消点赞
    @Override
    public Integer delete(Comment comment) {
        //删除comment表数据
        Query query = Query.query(Criteria.where("publishId").is(comment.getPublishId()).and("userId").is(comment.getUserId()).and("commentType").is(comment.getCommentType()));
        mongoTemplate.remove(query,Comment.class);
        //修改动态表中的总数量
        Query query2 = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if(comment.getCommentType()== CommentType.LIKE.getType()){
            update.inc("likeCount",-1);
        }else if (comment.getCommentType()== CommentType.COMMENT.getType()){
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        FindAndModifyOptions op = new FindAndModifyOptions();
        op.returnNew(true);
        Movement resMovement = mongoTemplate.findAndModify(query2, update, op, Movement.class);
        return resMovement.statisCount(comment.getCommentType());
    }

    public Integer saveComent(Comment comment) {
        //1.查询动态
        Comment movement = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //2.向comment对象设置被评论人属性
        if (movement != null) {
            comment.setPublishUserId(movement.getUserId());
        }
        //3.保存到数据库
        mongoTemplate.save(comment);
        //4.更新动态表中的对应字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        /* Comment modify =*/
        Comment modify = mongoTemplate.findAndModify(query, update, options, Comment.class);

        //5.获取最新评论数,并返回
        //mongoTemplate.findOne(query, Movement.class)
        return modify.getLikeCount();
    }

    @Override
    public Integer deleteCount(Comment comment) {
        //1.删除comment表数据 用户id 动态id 操作类型
        Criteria criteria = Criteria.where("UserId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Comment.class);

        //2.修改动态表的总数量
        //4.更新动态表中的对应字段
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//获取更新后的最新数据
        Comment modify = mongoTemplate.findAndModify(movementQuery, update, options, Comment.class);
        return modify.getLikeCount();
    }
    // 分页查询评论该用户的评论列表
    @Override
    public List<Comment> getComments(Long userId, Integer page, Integer pagesize) {
        // 根据用户id查询评论该用户的评论列表
        Pageable pageable = PageRequest.of(page-1,pagesize,Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(CommentType.COMMENT.getType())).with(pageable);
        return mongoTemplate.find(query, Comment.class);
    }

    // 分页查询点赞该用户的评论列表
    @Override
    public List<Comment> getLikes(Long userId, Integer page, Integer pagesize) {
        // 根据用户id查询点赞该用户的点赞列表
        Pageable pageable = PageRequest.of(page-1,pagesize,Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(CommentType.LIKE.getType())).with(pageable);
        return mongoTemplate.find(query, Comment.class);
    }

    // 分页查询喜欢该用户的喜欢列表
    @Override
    public List<Comment> getLoves(Long userId, Integer page, Integer pagesize) {
        // 根据用户id查询喜欢该用户的喜欢列表
        Pageable pageable = PageRequest.of(page-1,pagesize,Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(CommentType.LOVE.getType())).with(pageable);
        return mongoTemplate.find(query, Comment.class);
    }

    @Override
    public List<Comment> getlist(Integer page, Integer pagesize, String sortProp, String sortOrder, Long messageID) {

        Criteria criteria = Criteria.where("pid").is(messageID);
        Query query = new Query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        if (sortOrder != null && sortProp != null) {
            //这是排序字段和排序方式 两个都要不为null
            if ("ascending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.asc(sortProp)));

            } else if ("descending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.desc(sortProp)));
            }

        }
        List<Comment> comments = mongoTemplate.find(query, Comment.class);


        return comments;
    }

}
